package com.lzx.iteam.net;

import android.content.Context;
import android.os.Message;
import android.util.Log;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.provider.AttendanceCalendarDB;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.provider.ScheduleDB;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import static android.R.attr.value;

/**
 *
 */
public class GetAttendanceCalendarMsg extends CcMsgStructure {

    private static final String TAG = "GetAttendanceCalendarMsg";
    private Message mmCallback;
    private Context mContext;
    private String mYear, mMonth, mDay;
    private String mDate;
    private String mUserId;
    private String mGroupId;
    private AttendanceCalendarDB mAttendanceCalendarDB;
    private CloudDBOperation mCloudDBOperation;

    public GetAttendanceCalendarMsg(Message callback, Context mContext, String year, String month, String day, String boss, String groupId) {
        this.mmCallback = callback;
        this.mContext = mContext;
        this.mYear = year;
        this.mMonth = month;
        this.mDay = day;
        this.mUserId = boss;
        this.mGroupId = groupId;
        mAttendanceCalendarDB = new AttendanceCalendarDB(mContext);
        mCloudDBOperation = new CloudDBOperation(mContext);
        mDate = mYear + "_" + mMonth;
    }


    @Override
    public void onReceive(JSONObject data) {

        List<AttendanceCalendarData> attendanceCalendarDatas = new ArrayList<AttendanceCalendarData>();
        HashMap<String,List<Object>> atDatas = new HashMap<>();
//        List<Object> datas = new ArrayList<Object>();
        try {
            mCloudDBOperation.deleteAttendanceCalendarByDate(mUserId, mYear, mMonth, mGroupId);
            mAttendanceCalendarDB.deleteAttendanceByDate(mDate, mUserId, mGroupId);
            if (!data.isNull(AsynHttpClient.KEY_CC_DATA)) {
                JSONObject jsonObject = data.getJSONObject(AsynHttpClient.KEY_CC_DATA);
                JSONArray jsonArray = jsonObject.getJSONArray(AsynHttpClient.KEY_ATTENDANCE_CALENDARS);
                for (int i = 0; i < jsonArray.length(); i++) {
                    List<Object> datas = new ArrayList<Object>();
                    AttendanceCalendarData attendanceCalendarData = new AttendanceCalendarData();
                    JSONObject item = jsonArray.getJSONObject(i);
                    attendanceCalendarData.setStatus(item.getString("status"));
                    if (item.has("cheat")) {
                        attendanceCalendarData.setCheat(item.getString("cheat"));
                    }
                    attendanceCalendarData.setDay(item.getString("day"));
                    attendanceCalendarData.setYear(mYear);
                    attendanceCalendarData.setMonth(mMonth);
                    attendanceCalendarData.setUserId(mUserId);
                    attendanceCalendarData.setGroupId(mGroupId);
                    if (item.has("is_legwork")) {
                        attendanceCalendarData.setIsLegwork(item.getString("is_legwork"));
                    }
                    attendanceCalendarDatas.add(attendanceCalendarData);
                    mCloudDBOperation.insertAttendanceCalendarListData(attendanceCalendarData);

                    if (item.has("items")) {
                        JSONArray items = item.getJSONArray("items");
                        if (items.length() > 0) {
                            for (int j = 0; j < items.length(); j++) {
                                JSONObject details = items.getJSONObject(j);
                                AttendanceCalendarMsgData attendanceCalendarMsgData = new AttendanceCalendarMsgData();
                                attendanceCalendarMsgData.setType(details.getString("type"));
                                attendanceCalendarMsgData.setDay(item.getString("day"));
                                attendanceCalendarMsgData.setGroup_id(mGroupId);
                                attendanceCalendarMsgData.setUser_id(mUserId);
                                if (details.has("part")) {
                                    attendanceCalendarMsgData.setPart(details.getString("part"));
                                }
                                JSONObject detail = details.getJSONObject("detail");
                                attendanceCalendarMsgData.set_id(detail.getString("_id"));
                                attendanceCalendarMsgData.setAtten_calendar_id(item.getString("_id"));
                                if ("1".equals(details.getString("type"))) {//打卡
                                    attendanceCalendarMsgData.setStatus(detail.getString("status"));
                                    attendanceCalendarMsgData.setForm_id(detail.getString("form_id"));
                                    attendanceCalendarMsgData.setLongitude(detail.getString("longitude"));
                                    attendanceCalendarMsgData.setLatitude(detail.getString("latitude"));
                                    attendanceCalendarMsgData.setDate(detail.getString("date"));
                                    attendanceCalendarMsgData.setPart(detail.getString("part"));
                                    attendanceCalendarMsgData.setTime(detail.getString("time"));

                                    if (detail.has("cheat")) {
                                        attendanceCalendarMsgData.setCheat(detail.getString("cheat"));
                                    }
                                    if (detail.has("cheat_device_id")) {
                                        attendanceCalendarMsgData.setCheat_device_id(detail.getString("cheat_device_id"));
                                    }
                                } else {
                                    attendanceCalendarMsgData.setStatus(item.getString("status"));
                                    if (detail.has("approval_end_part")){
                                        attendanceCalendarMsgData.setApproval_end_part(detail.getString("approval_end_part"));
                                    }
                                    if (detail.has("approval_end_time")){
                                        attendanceCalendarMsgData.setApproval_end_time(detail.getString("approval_end_time"));
                                    }
                                    attendanceCalendarMsgData.setApproval_status(detail.getString("approval_status"));
                                    attendanceCalendarMsgData.setApproval_reason(detail.getString("approval_reason"));
                                    attendanceCalendarMsgData.setApproval_type(detail.getString("approval_type"));
                                    attendanceCalendarMsgData.setApproval_done_time(detail.getString("approval_done_time"));
                                    if (detail.has("approval_address")){
                                        attendanceCalendarMsgData.setApproval_address(detail.getString("approval_address"));
                                    }
                                    attendanceCalendarMsgData.setForm_id(detail.getString("approval_form_id"));
                                    if (detail.has("approval_leave_type")){
                                        attendanceCalendarMsgData.setApproval_leave_type(detail.getString("approval_leave_type"));
                                    }
                                    attendanceCalendarMsgData.setApprove_admin(detail.getString("approve_admin"));
                                    if (detail.has("approval_day")){
                                        attendanceCalendarMsgData.setApproval_day(detail.getString("approval_day"));
                                    }
                                    attendanceCalendarMsgData.setApproval_start_time(detail.getString("approval_start_time"));
                                    attendanceCalendarMsgData.setApproval_time(detail.getString("approval_time"));
                                    attendanceCalendarMsgData.setApproval_start_part(detail.getString("approval_start_part"));
                                }
                                datas.add(attendanceCalendarMsgData);
//                                mAttendanceCalendarDB.addAttendanceCalendar("0",mDate, item.getString("day"), attendanceCalendarMsgData);
                            }

                        }
                    }

                    if (item.has("legwork")) {
                        JSONArray items = item.getJSONArray("legwork");
                        if (items.length() > 0) {
                            for (int j = 0; j < items.length(); j++) {
                                JSONObject details = items.getJSONObject(j);
                                LegworkRecordData legworkRecordData = new LegworkRecordData();
                                legworkRecordData.setTime(details.getString("time"));
                                legworkRecordData.setRemark(details.getString("remark"));
                                legworkRecordData.setLongitude(details.getDouble("longitude"));
                                legworkRecordData.setLatitude(details.getDouble("latitude"));
                                legworkRecordData.setAddress(details.getString("address"));
                                legworkRecordData.setDay(details.getString("day"));
                                legworkRecordData.setGroupId(mGroupId);
                                legworkRecordData.setUserId(mUserId);
                                if (details.has("attachment")) {
                                    legworkRecordData.setAttachment(details.getJSONArray("attachment").toString());
                                }
                                datas.add(legworkRecordData);
//                                mAttendanceCalendarDB.addAttendanceCalendar("-1",mDate, item.getString("day"), legworkRecordData);
                            }

                        }
                    }
                    atDatas.put(item.getString("day"),datas);
                }
                Iterator iterator = atDatas.keySet().iterator();
                while (iterator.hasNext()){
                    String key = (String) iterator.next();
                    List<Object> at = atDatas.get(key);
                    for (int i = 0; i < at.size(); i++) {
                        Object object = at.get(i);
                        if (object instanceof AttendanceCalendarMsgData){
                            mAttendanceCalendarDB.addAttendanceCalendar("0",mDate, key, object);
                        }else if (object instanceof LegworkRecordData){
                            mAttendanceCalendarDB.addAttendanceCalendar("-1",mDate, key, object);
                        }
                    }
                }

            }
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("calendar", attendanceCalendarDatas);
            map.put("attendance", atDatas.get(mDay));

            if (mmCallback != null) {
                mmCallback.arg1 = 0;
                mmCallback.obj = map;
                mmCallback.sendToTarget();
            }

        } catch (Exception e) {
            Log.e(TAG, "error:   " + e.toString());
            e.printStackTrace();
        }
    }


    @Override
    public void onError(int error, Object ret) {
        Log.d(TAG, "onError : " + error + " ret: " + ret);
        String errorMsg = null;
        if (ret != null) {
            JSONObject jData = null;
            try {
                jData = new JSONObject(ret.toString());
                errorMsg = jData.getString("msg");
            } catch (JSONException e) {
                errorMsg = "服务端数据解析失败!";
                e.printStackTrace();
            }

        }
        if (mmCallback != null) {
            mmCallback.arg1 = error;
            if (!StringUtil.isEmpty(errorMsg)) {
                mmCallback.obj = errorMsg;
            } else {
                mmCallback.obj = Constants.NETWORK_WRROR;
            }
            mmCallback.sendToTarget();
        }
    }
}
